<!-- ^2_3^ -->
<template>
  <a-modal
    :title="title"
    :width="640"
    :visible="visible"
    :confirmLoading="loading"
    @ok="() => { $emit('ok') }"
    @cancel="() => { $emit('cancel') }"
  >
    <a-spin :spinning="loading">
      <a-form :form="form" v-bind="formLayout">
        <a-form-item v-show="model && model.id > 0" label="管理ID">
          <a-input v-decorator="['id', { initialValue: 0 }]" disabled />
        </a-form-item>
        <a-form-item label="账号名称">
          <a-input v-decorator="['username', {rules: [{required: true, min: 1, message: '请输入至少1个字符'}]}]" />
        </a-form-item>
        <a-form-item label="账号密码">
          <a-input
            v-decorator="['password', {}]"
            type="password"
            placeholder="" />
        </a-form-item>
        <a-form-item label="状态">
          <a-radio-group v-decorator="['status', { initialValue: 1 }]">
            <a-radio :value="0">禁用</a-radio>
            <a-radio :value="1">正常</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="角色授权">
          <a-select
            mode="multiple"
            style="width: 100%"
            placeholder="Please select"
            v-decorator="['roles', {}]"
            @change="handleChange"
          >
            <a-select-option v-for="item in roleList" :key="item.key">
              {{ item.r_name }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
// ^2_3^
import pick from 'lodash.pick'
import { roleValid } from '@/api/role'

// 表单字段
const fields = ['id', 'username', 'status', 'roles']

export default {
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    loading: {
      type: Boolean,
      default: () => false
    },
    model: {
      type: Object,
      default: () => null
    }
  },
  data () {
    this.formLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 13 }
      }
    }
    return {
      form: this.$form.createForm(this),
      roleList: []
    }
  },
  methods: {
    handleChange (value) {
      console.log(`selected ${value}`)
    },
    roleHandle () {
      return roleValid().then(res => {
        this.roleList = res.data
      })
    }
  },
  created () {
    // 防止表单未注册
    fields.forEach(v => this.form.getFieldDecorator(v))

    // 当 model 发生改变时，为表单设置值
    this.$watch('model', () => {
      this.model && this.form.setFieldsValue(pick(this.model, fields))
    })

    this.roleHandle()
  },
  computed: {
    title () {
      return this.model === null ? '账号新增' : '账号更新'
    }
  }
}
</script>
